<?php

namespace backend\controllers;
use Yii;
use yii\web\Controller;
use backend\models\right\JobRight;
use backend\models\admin\JobAdmin;
use backend\models\right\JobAdminRelation;
header('content-type:text/html;charset=utf8');
class CommontController extends Controller 
{
    public function init() 
    {    
    	//自动执行方法 判断session是否登录 没有登录跳转登录界面
    	if(empty(Yii::$app->session['admin_name']))
	        { 
	        echo "<script>alert('未登录，请先登录！');
	            location.href='?r=login/index'</script>";exit;
	        }

	    if (Yii::$app->request->isGet) 
	    {   
	    	$admin_name = Yii::$app->session['admin_name'];
	    	$right_name = Yii::$app->request->get('r');
	    	if ($admin_name!="admin") 
	    	{   
	    		if ($right_name=="index/index") 
	    		{
	    			return true;
	    		}
	    		$admin_db = JobAdmin::find()->where(['admin_name'=>$admin_name])->One();
	    		$admin_id = $admin_db->id;
	    		$admin_relation = JobAdminRelation::find()->where(['admin_id'=>$admin_id])->All();
	    		$right_status = false;
	    		foreach ($admin_relation as $key => $value) 
	    		{
	    			$right = JobRight::find()->where(['id'=>$value->right_id])->One();
	    			if ($right_name==$right->right) 
	    			{
	    				$right_status= true;
	    			}
	    		}
	    		if ($right_status==false) 
	    		{
	    			echo "<script>alert('您没有此权限！');
    				location.href='?r=index/index'</script>";exit;
	    		}
	    		
	    	}



	    }
    }
	public function NodeOrder($data,$p_id,$pid=0,$a=0){
		$res = [];
		//print_r($p_id);exit;
		foreach ($data as $key => $value) {
			if ($value[$p_id] == $pid) {
				$value['a']=$a;
				$res[] = $value;
				$res=array_merge($res,$this->NodeOrder($data,$p_id,$value['id'],$a+1));
			}
		}
		return $res;
	}

	public function findChild(&$data,$pid){
		  $res=[];
		  foreach ($data as $k => $v){
		   if($v['p_id']== $pid){
		    $res[]=$v;
		   }
		  }
		  return $res;
	 }
	public function build_tree($data,$pid=0){
		$res=$this->findChild($data,$pid);
			if(empty($res)){
				return null;
		  	}
		foreach ($res as $k => $v){
			$rescurTree=$this->build_tree($data,$v['id']);
			if( null != $rescurTree){
				$res[$k]['a']=$rescurTree;
		  	}
		}
		return $res;
	}
}
?>
